import React, { useState, useEffect } from 'react';
import { useRoute } from '@react-navigation/native';
import { View, Text, TextInput, Pressable, FlatList, StyleSheet, Image } from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
import axios from 'axios';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { useNavigation } from '@react-navigation/native';
import CommentInput from './CommentInput';

const SearchPlateContent = () => {
    const navigation = useNavigation();
    const [searchQuery, setSearchQuery] = useState('');
    const [selectedTab, setSelectedTab] = useState('热度');
    const route = useRoute();
    const [boardName, setboardName] = useState(route.params?.boardName || '');
    const [posts, setPosts] = useState([
        // 假设的帖子数据
        // ...
    ]);
    const [timePosts, setTimePosts] = useState([]);
    const [postID, setPostID] = useState(null);
    const [likes, setLikes] = useState([]);
    const [liked, setLiked] = useState([]);
    const [view, setView] = useState([]);
    const [userInfo, setUserInfo] = useState({});
    const [comments, setComments] = useState([]);
    const [commentIndex, setCommentIndex] = useState(null);
    const [isCommentInputVisible, setIsCommentInputVisible] = useState(false);
    const [time, setTime] = useState('');

    const getDynamicBoardByView = async () => {
        const url = selectedTab === '热度'
            ? 'http://47.111.227.58:3000/dynamic/getdynamicByBoardView'
            : 'http://47.111.227.58:3000/dynamic/getdynamicByBoardTime';
        axios.get(url, {
            params: {
                board: boardName,
            },
        })
            .then(res => {
                // console.log(res.data);
                setPosts(res.data.results)
                const initialLikes = res.data.results.map(item => item.likes);
                setLikes(initialLikes);
                const initialLiked = res.data.results.map(item => item.likedUsers?.split(',').includes(userInfo.username));
                setLiked(initialLiked);
                const initialView = res.data.results.map(item => item.view);
                setView(initialView)
                const initialComments = res.data.results.map(item => item.comments);
                setComments(initialComments);
            })
            .catch(error => {
                console.error('Error fetching data:', error);
            });
    }
    const getdynamicByContentAndBoard = async () => {
        const url = selectedTab === '热度'
            ? 'http://47.111.227.58:3000/dynamic/getdynamicByContentAndBoard'
            : 'http://47.111.227.58:3000/dynamic/getdynamicByContentAndBoardByTime';
        axios.get(url, {
            params: {
                board: boardName,
                content: searchQuery
            },
        })
            .then(res => {
                // console.log(res.data);
                setPosts(res.data.results)
                const initialLikes = res.data.results.map(item => item.likes);
                setLikes(initialLikes);
                const initialLiked = res.data.results.map(item => item.likedUsers?.split(',').includes(userInfo.username));
                setLiked(initialLiked);
                const initialView = res.data.results.map(item => item.view);
                setView(initialView)
                const initialComments = res.data.results.map(item => item.comments);
                setComments(initialComments);
            })
            .catch(error => {
                console.error('Error fetching data:', error);
            });
    }
    const handleLike = (postId, index) => {
        console.log(liked)
        if (liked[index]) {
            // 如果用户已经点过赞，那么再次点击就取消点赞
            let newLikes = [...likes];
            newLikes[index] = Number(newLikes[index]) - 1;
            setLikes(newLikes);
            let newLiked = [...liked];
            newLiked[index] = false;
            setLiked(newLiked);
            axios.post('http://47.111.227.58:3000/dynamic/updataIdDynamicLikes', {
                data: {
                    id: postId,
                    likes: newLikes[index]
                }
            }).then(res => {
                // console.log(res.data);
                // 更新点赞用户列表
                axios.post('http://47.111.227.58:3000/dynamic/updateLikedUsers', {
                    postId: postId,
                    userId: userInfo.username
                }).then(res => {
                    // console.log(res.data);
                });
            });
        } else {
            // 如果用户还没点过赞，那么点击就增加点赞
            let newLikes = [...likes];
            newLikes[index] = Number(newLikes[index]) + 1;
            setLikes(newLikes);
            let newLiked = [...liked];
            newLiked[index] = true;
            setLiked(newLiked);
            axios.post('http://47.111.227.58:3000/dynamic/updataIdDynamicLikes', {
                data: {
                    id: postId,
                    likes: newLikes[index]
                }
            }).then(res => {
                // console.log(res.data);
                // 更新点赞用户列表
                axios.post('http://47.111.227.58:3000/dynamic/updateLikedUsers', {
                    postId: postId,
                    userId: userInfo.username
                }).then(res => {
                    // console.log(res.data);
                });
            });
        }
    };

    const handlePostClick = (postId, index) => {
        navigation.navigate('PostDetail', { postId: postId });
        let newView = [...view];
        newView[index] = Number(newView[index]) + 1;
        setView(newView);
        axios.post('http://47.111.227.58:3000/dynamic/updataIdDynamicView', {
            data: {
                id: postId,
                view: newView[index]
            }
        }).then(res => {
            // console.log(res.data);
        });
    };
    const handleHideCommentInput = () => {
        if (isCommentInputVisible) {
            setIsCommentInputVisible(false);
        }
    };
    const getFormattedCurrentTime = () => {
        const now = new Date(); // 获取当前时间
        const year = now.getFullYear(); // 年
        const month = (now.getMonth() + 1).toString().padStart(2, '0'); // 月，月份是从0开始计数的
        const day = now.getDate().toString().padStart(2, '0'); // 日
        const hours = now.getHours().toString().padStart(2, '0'); // 时
        const minutes = now.getMinutes().toString().padStart(2, '0'); // 分
        const seconds = now.getSeconds().toString().padStart(2, '0'); // 秒

        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }
    const onCommentSubmit = (comment) => {
        console.log('评论提交：', comment);
        // console.log(userInfo)
        const currentTime = getFormattedCurrentTime();
        setTime(currentTime)

        if (comment != '') {
            axios.post('http://47.111.227.58:3000/dynamic/addcomments', {
                data: {
                    dy_id: postID,
                    username: userInfo.username,
                    phone: userInfo.phone,
                    userImg: userInfo.imgUrl,
                    content: comment,
                    uploadTime: time
                }
            }).then(res => {
                console.log(res.data)
                let newComment = [...comments];
                newComment[commentIndex] = Number(newComment[commentIndex]) + 1;
                setComments(newComment);
                axios.post('http://47.111.227.58:3000/dynamic/updataIdDynamicComments', {
                    data: {
                        id: postID,
                        comment: newComment[commentIndex]
                    }
                }).then(res => {
                    // console.log(res.data);
                });
            })
        }
        setIsCommentInputVisible(false);
    }
    useEffect(() => {
        (async () => {
            const userinfo = await AsyncStorage.getItem('userInfo');
            if (userinfo) {
                setUserInfo(JSON.parse(userinfo))
            }
        })();
    }, []);
    useEffect(() => {
        (async () => {
            // 如果route.params.query存在，则设置为searchInput的值
            if (route.params) {
                setboardName(route.params?.boardName);
            }
            console.log(route.params)
        })();
    }, [route.params]);
    useEffect(() => {
        if (userInfo.username) {
            getdynamicByContentAndBoard()
        }
    }, [userInfo]);
    useEffect(() => {
        getdynamicByContentAndBoard()
    }, [selectedTab]);
    useEffect(() => {
        getdynamicByContentAndBoard()
    }, [boardName]);


    const renderItem = ({ item, index }) => {
        return (
            <Pressable onPress={() => handlePostClick(item.id, index)}>
                <View style={styles.messageItem}>
                    <View style={styles.messageHeader}>
                        <Image style={styles.avatar} source={{ uri: item.userImg }} />
                        <Text style={styles.username}>{item.username}</Text>
                        <Text style={styles.uploadTime}>{item.uploadTime}</Text>
                    </View>
                    <Text style={styles.messageText}>{item.desc}</Text>
                    {item.imgUrl && (
                        <Image style={styles.messageImage} source={{ uri: item.imgUrl }} />
                    )}
                    <Text style={styles.boardText}>#{item.board}</Text>
                    <View style={styles.interactionBar}>
                        <View style={styles.leftInteractions}>
                            <Pressable style={styles.interactionButton}>
                                <Icon name="tags" size={18} color="#b8b8b8" style={{ marginRight: 5 }} />
                                <Text>马住</Text>
                            </Pressable>
                            <Pressable style={styles.interactionButton}>
                                <Icon name="certificate" size={18} color="#b8b8b8" style={{ marginRight: 5 }} />
                                <Text>赞赏</Text>
                            </Pressable>
                            <Pressable style={styles.interactionButton} onPress={() => handleLike(item.id, index)}>
                                <Icon name={liked[index] ? 'thumbs-up' : 'thumbs-o-up'} size={18} color="#b8b8b8" style={{ marginRight: 5 }} />
                                <Text>{likes[index] > 0 ? likes[index] : '点赞'}</Text>
                            </Pressable>
                        </View>

                        <Pressable
                            style={styles.rightInteraction}
                            onPress={() => { setCommentIndex(index); setPostID(item.id); setIsCommentInputVisible(true) }}
                        >
                            <Icon name="pencil-square-o" size={18} color="#b8b8b8" style={{ marginRight: 5, marginLeft: 5 }} />
                            <Text style={{ marginRight: 5 }}>{comments[index] > 0 ? comments[index] : '评论'}</Text>
                        </Pressable>
                    </View>
                </View>
            </Pressable>
        );
    };

    return (
        <View style={styles.container}>
            <View style={styles.header}>
                <Pressable onPress={() => navigation.navigate('ChooseplateBoard')}>
                    <Text style={styles.category}>{boardName ? boardName : '分类模块'}</Text>
                </Pressable>
                <View style={styles.searchInput}>
                    <Icon name="search" size={20} color="#FCF9F5" style={styles.searchIcon} />
                    <TextInput
                        value={searchQuery}
                        onChangeText={setSearchQuery}
                        placeholder="搜索"
                        placeholderTextColor="#FCF9F5" // 占位符文字颜色
                        style={{ flex: 1 }} // 确保TextInput占满剩余空间
                        onSubmitEditing={getdynamicByContentAndBoard}
                    />
                </View>
            </View>
            <View style={styles.tabBar}>
                <Pressable
                    style={[styles.tabItem, selectedTab === '热度' && styles.tabItemSelected]}
                    onPress={() => setSelectedTab('热度')}
                >
                    <Text style={styles.tabText}>热度</Text>
                </Pressable>
                <Pressable
                    style={[styles.tabItem, selectedTab === '最新' && styles.tabItemSelected]}
                    onPress={() => setSelectedTab('最新')}
                >
                    <Text style={styles.tabText}>最新</Text>
                </Pressable>
            </View>
            <FlatList
                data={posts}
                renderItem={renderItem}
                keyExtractor={item => item.id}
            />
            {isCommentInputVisible && (
                <>
                    <Pressable
                        style={StyleSheet.absoluteFill}
                        activeOpacity={1}
                        onPress={handleHideCommentInput}
                    />
                    <CommentInput
                        onCommentSubmit={onCommentSubmit}
                        isKeyboardVisible={isCommentInputVisible}
                        setIsKeyboardVisible={setIsCommentInputVisible}
                    />
                </>
            )}
        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    header: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        padding: 10,
        backgroundColor: '#EB7A76',
    },
    category: {
        backgroundColor: '#BC635F',
        borderRadius: 20,
        paddingVertical: 5,
        paddingHorizontal: 15,
        color: '#FCF9F5',
        marginHorizontal: 10,
    },
    searchInput: {
        flex: 1,
        flexDirection: 'row',
        alignItems: 'center',
        backgroundColor: '#BC635F',
        borderRadius: 20,
        paddingVertical: 5,
        paddingHorizontal: 15,
        marginHorizontal: 10,
    },
    searchIcon: {
        marginRight: 10,
    },
    tabBar: {
        flexDirection: 'row',
        justifyContent: 'space-around',
        backgroundColor: '#f8f8f8',
    },
    tabItem: {
        padding: 10,
    },
    tabItemSelected: {
        borderBottomWidth: 2,
        borderBottomColor: '#000',
    },
    tabText: {

    },
    postItem: {
        flexDirection: 'row',
        padding: 10,
        borderBottomWidth: 1,
        borderBottomColor: '#eee',
    },
    postImage: {
        width: 50,
        height: 50,
        borderRadius: 25,
    },
    postContent: {
        marginLeft: 10,
        justifyContent: 'center',
    },
    postTitle: {
        fontWeight: 'bold',
    },
    postDetails: {
        color: '#888',
    },
    messageItem: {
        backgroundColor: '#fff',
        padding: 10,
        borderBottomWidth: 1,
        borderBottomColor: '#eee',
        marginBottom: 10,
        paddingLeft: 15,
    },
    messageHeader: {
        flexDirection: 'row',
        alignItems: 'center',
        marginBottom: 5,
    },
    avatar: {
        width: 40,
        height: 40,
        borderRadius: 20,
        marginRight: 10,
        borderWidth: 1,
        borderColor: '#ddd',
    },
    messageImage: {
        width: '70%',
        height: 170,
        borderRadius: 5,
        marginBottom: 5,
        borderWidth: 1,
        borderColor: '#ddd',
        marginBottom: 10,
    },
    username: {
        fontWeight: 'bold',
    },
    uploadTime: {
        // fontWeight: 'bold',
        color: '#b8b8b8',
        fontSize: 12,
        marginLeft: 'auto',
        marginRight: 5,
    },
    messageText: {
        marginBottom: 5,
    },
    boardText: {
        height: 25,
        width: 60,
        backgroundColor: '#DDE1EA',
        color: '#576B94',
        marginBottom: 5,
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        fontSize: 12,
        // fontWeight: 'bold',
    },
    interactionBar: {
        flexDirection: 'row',
        justifyContent: 'space-between', // 确保内容分布在两侧
        alignItems: 'center', // 垂直居中
    },
    leftInteractions: {
        flexDirection: 'row', // 使得按钮水平排列
    },
    rightInteraction: {
        flexDirection: 'row',
        borderWidth: 1,
        borderColor: '#ccc',
        borderRadius: 20,
        padding: 5,
    },
    interactionButton: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingRight: 15,
    },
    commentButton: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingLeft: 10,
        paddingRight: 10,
        borderWidth: 1,
        borderColor: '#ccc',
        borderRadius: 20,
        padding: 5,
    },
    commentInput: {
        borderColor: '#ccc',
    },
});

export default SearchPlateContent;
